<template>
  <div class="app-container">
    <el-form inline>
      <!-- 表单元素 -->
      <el-form-item>
        <el-input
          placeholder="用户名"
          size="small"
          v-model="tempSearchObj.username"
        ></el-input>
      </el-form-item>
      <!-- 查询和清空按钮 -->
      <el-button
        type="primary"
        icon="el-icon-search"
        round
        size="small"
        @click="search"
        >查询</el-button
      >
      <el-button type="default" round size="small" @click="resetSearch"
        >清空</el-button
      >
    </el-form>
    <!-- 添加和批量删除按钮 -->
    <div class="mb-20">
      <el-button type="primary" round size="small" @click="showAddUser"
        >添加</el-button
      >
      <el-button
        type="danger"
        round
        size="small"
        @click="revomveUsers"
        :disabled="selectedIds.length === 0"
        >批量删除</el-button
      >
    </div>
    <!-- 表格 -->
    <el-table border stripe class="mb-5" :data="users" v-loading="listLoading">
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column type="index" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="150">
      </el-table-column>
      <el-table-column prop="nickName" label="用户昵称"> </el-table-column>
      <el-table-column prop="roleName" label="角色列表" width="200">
      </el-table-column>
      <el-table-column
        prop="gmtCreate"
        label="创建时间"
        width="180"
      ></el-table-column>
      <el-table-column prop="gmtModified" label="更新时间" width="180">
      </el-table-column>
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="{ row, $index }">
          <el-button
            type="info"
            size="small"
            icon="el-icon-user-solid"
            circle
            title="分配角色"
            @click="showAssignRole(row)"
          ></el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit-outline"
            circle
            title="修改用户"
            @click="showUpdateUser(row)"
          ></el-button>

          <el-popconfirm
            :title="`确认删除${row.username}吗？`"
            @onConfirm="removeUser(row.id)"
          >
            <el-button
              slot="reference"
              type="danger"
              size="small"
              icon="el-icon-delete"
              circle
              title="删除用户"
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="getUserList"
      :current-page="page"
      :page-sizes="[3, 6, 9]"
      :page-size="limit"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      :pager-count="5"
    >
    </el-pagination>
    <!-- 对话框的结构 -->
    <el-dialog
      :title="user.id ? '添加用户' : '添加用户'"
      :visible.sync="dialogUserVisible"
      width="30%"
    >
      <el-form
        ref="userForm"
        :model="user"
        :rules="userRules"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username" />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="user.nickName" />
        </el-form-item>
        <el-form-item v-if="!user.id" label="用户密码" prop="password">
          <el-input v-model="user.password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button round size="small">取 消</el-button>
        <!-- @click="cancel" -->
        <!-- @click="addOrUpdate" -->
        <el-button round size="small" type="primary">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="设置角色"
      :visible.sync="dialogRoleVisible"
      :before-close="resetRoleData"
    >
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input disabled :value="user.username"></el-input>
        </el-form-item>

        <el-form-item label="角色列表">
          <!-- 
            v-model 布尔值,控制选中和不选中状态
            indeterminate 布尔值,为true的时候是半选状态
          -->
          <el-checkbox
            :indeterminate="isindeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="userRoleIds"
            @change="handleCheckedChange"
          >
            <el-checkbox
              v-for="role in allRoles"
              :key="role.id"
              :label="role.id"
              >{{ role.rolename }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button type="primary" :loading="loading" @click="assignRole"
          >保存</el-button
        >
        <el-button @click="resetroleData">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    return {
      listLoading: true, // 是否显示列表加的提示
      dialogUserVisible: false, // 是否显示用户添加/修改的dialog
      searchObj: {
        // 包含请求搜索条件数据的对象
        username: "",
      },
      tempSearchObj: {
        // 收集搜索条件输入的对象
        username: "",
      },
      page: 1, // 当前页码
      limit: 3, // 每页数量
      total: 0, // 总数量
      selectedIds: [], // 所有选择的user的id的数组
      users: [], // 当前页的用户列表
      user: {}, // 当前要换作的user
      checkAll: false, // 是否全选
      userRules: {
        // 用户添加/修改表单的校验规则
        username: [
          { required: true, message: "用户名必须输入" },
          { min: 4, message: "用户名不能小于4位" },
        ],
        password: [{ required: true, validator: this.validatePassword }],
      },
      loading: false, // 是否正在提交请求中
      dialogRolevisible: false, // 是否显示角色
      allRoles: [], // 所有角色列表
      userRoleIds: [], // 用户的角色ID的列表
      isIndeterminate: false, // 是否是不确定的
    };
  },
  mounted() {
    this.getUserList();
    this.getUserRoleList();
  },
  methods: {
    // 展示指定角色的界面
    showAssignRole(user) {
      this.user = user;
      this.dialogUserVisible = true;
      this.getRoles();
    },
    // 全部勾选状态下发生变化的监听
    handleCheckAllChange(value) {
      this.userRoleIds = value ? this.allRoles.map((item) => item.id) : [];
      this.isIndeterminate = false;
    },
    // 异步获取用户角色的列表
    async getRoles() {
      const result = await this.$api.getUserRoleListApi(this.user.id);
      const { allRolesList, assignRoles } = result.data;
      this.allRoles = allRolesList;
      this.userRoleIds = assignRoles.map((item) => item.id);
      this.checkAll = allRolesList.length === assignRoles.length;
      this.isIndeterminate =
        assignRoles.length > 0 && assignRoles.length < allRolesList.length;
    },
    // 角色列表选中想发送变化的监听
    handleCheckedChange(value) {
      const { userRoleIds, allRoles } = this;
      this.checkAll =
        userRoleIds.length === allRoles.length && allRoles.length > 0;
      this.isIndeterminate =
        userRoleIds.length > 0 && userRoleIds.length < allRoles.length;
    },
    // 请求给用户进行角色授权
    async assignRole() {
      const userId = this.user.id;
      const roleIds = this.userRoleIds.join(",");
      this.loading = true;
      let result = await this.$api.getUserRoleListApi(userId, roleIds);
      // console.log(result);
      this.loading = false;
      this.$message.success(result.message || "分配角色成功");
      this.resetRoleData();
    },

    // 重置用户角色的数据
    resetRoleData() {
      this.dialogRolevisible = false;
      this.allRoles = [];
      this.userRoleIds = [];
      this.isIndeterminate = false;
      this.checkAll = false;
    },
    // 自定义密码校验
    validatePassword(rule, value, callback) {
      if (!value) {
        callback("密码必须输入");
      } else if (!value || value.length < 6) {
        callback("密码不能小于6位");
      } else {
        callback();
      }
    },

    // 根据输入进行搜索
    search() {
      console.log(111);
      this.searchObj = { ...this.tempSearchObj };
      this.getUserList();
    },

    // 点击清空
    resetSearch() {
      this.searchObj = {
        username: "",
      };
      this.tempSearchObj = {
        username: "",
      };
      this.getUserList();
    },

    // 添加用户
    showAddUser() {
      this.user = {};
      this.dialogUserVisible = true;
      this.$nextTick(() => this.$refs.userForm.clearValidate());
    },

    // 批量删除
    revomveUsers() {
      this.$confirm("确定删除吗？")
        .then(async () => {
          await this.$api.removeUserApi(this.selectedIds);
          this.$message.success("删除成功");
          this.getUserList();
        })
        .catch(() => {
          this.$message.info("取消删除");
        });
    },
    // 列表选中状态发生改变的监听回调
    handleSelectionChange(selection) {
      this.selectedIds = selection.map((item) => item.id);
    },

    // 显示更新用户的界面

    // // 获取用户的角色列表
    // async getUserRoleList() {
    //   try {
    //     let result = await this.$api.getUserRoleListApi(userId);
    //     console.log(result);
    //   } catch (error) {
    //     this.$message.error("获取用户的角色列表失败，请重试");
    //   }
    // },
    // 获取分页列表
    async getUserList(page = 1) {
      try {
        this.page = page;
        const { limit, searchParams } = this;
        this.loading = true;
        let result = await this.$api.getUserListApi(page, limit, searchParams);
        this.loading = false;
        // console.log(result);
        const { items, total } = result.data;
        this.users = items.filter((item) => item.username != "admin");
        this.total = total - 1;
        this.selectedIds = [];
      } catch (error) {
        this.$message.error("获取分页列表失败，请重试");
      }
    },

    handleSizeChange(limit) {
      this.limit = limit;
      // 重新获取列表数据
      this.getUserList();
    },
    // handleCurrentChange(pager) {
    //   this.page = pager;
    //   // 重新获取列表数据
    //   this.getUserList();
    // },

    // 分配角色
    showAssignRole() {},
    // 修改用户
    showUpdateUser() {},
  },
};
</script>

<style scoped>
</style>